package com.meteor.downloader.videodownloader.activity.downloader

import android.content.ClipboardManager
import android.content.Intent
import android.view.View
import androidx.lifecycle.lifecycleScope
import coil.load
import coil.transform.RoundedCornersTransformation
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.meteor.downloader.videodownloader.R
import com.meteor.downloader.videodownloader.activity.MdmBindingActivity
import com.meteor.downloader.videodownloader.activity.set.MdmHelpYouActivity
import com.meteor.downloader.videodownloader.admdm.MdmDealAdUtils
import com.meteor.downloader.videodownloader.databinding.ActivityMdmInputLinkBinding
import com.meteor.downloader.videodownloader.dismissGoMdm
import com.meteor.downloader.videodownloader.mdmBaseResult64
import com.meteor.downloader.videodownloader.mdmGetPxDp
import com.meteor.downloader.videodownloader.mdmdata.DataDownloadingMdm
import com.meteor.downloader.videodownloader.mdmdata.DataLinkValueMdm
import com.meteor.downloader.videodownloader.showToastIDMdm
import com.meteor.downloader.videodownloader.utils.ApplicationMdmUtils
import com.meteor.downloader.videodownloader.utils.ApplicationMdmUtils.mVideoMdmList
import com.meteor.downloader.videodownloader.utils.DataManagerMdmUtils
import com.meteor.downloader.videodownloader.utils.MdmTotalUtils
import com.meteor.downloader.videodownloader.utils.dialog.DialogInitMdmLoading
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_ALL_TWO_KEY
import com.meteor.downloader.videodownloader.utils.value.ConstantMdm.MDM_ALL_TWO_KEY_VALUES
import com.meteor.downloader.videodownloader.utils.value.ParamsMdmUtils.mParseLinksList
import com.squareup.moshi.Moshi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import kotlin.random.Random

class MdmInputLinkActivity : MdmBindingActivity<ActivityMdmInputLinkBinding>() {
    private var mLinkSearch = ""
    private var mGoType = ""
    private var mDefaultUrl = ""
    private val mMdmClipText by lazy {
        getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
    }

    //蒙层
    private var mFirstMdm = false
    private var mClickDownload = false
    private var mDialogInitMdmLoading: DialogInitMdmLoading? = null
    private var mSearchCountMdm = 0
    private var mSearchText = ""
    private var mTempLink: String? = null

    override fun beginViewAndDoMdm() {
        mStarNativeValue = true
        mNativeBookLayout = mMdmBinding.flMdmNativeView
        intent?.let {
            mGoType = it.getStringExtra("goType") ?: ""
            mLinkSearch = it.getStringExtra("linkSearch") ?: ""
            mDefaultUrl = it.getStringExtra("defaultUrl") ?: ""
            mFirstMdm = it.getBooleanExtra("isFirst", false)
            mMdmBinding.layoutTopSet.tvTitleAll.text = when (mGoType) {
                "X" -> getString(R.string.mdm_)
                "Pinterest" -> getString(R.string.app_pinterest)
                else -> {
                    ""
                }
            }
            if (mLinkSearch.isNotEmpty()) {
                mClickDownload = true
                mMdmBinding.etInputLink.setText(mLinkSearch)
            } else {
                if (mFirstMdm) {
                    if (mVideoMdmList.isEmpty()) {
                        ApplicationMdmUtils.getMeteorVideoSome()
                    }
                    try {
                        val data = mVideoMdmList[Random.nextInt(0, 10)]
                        mMdmBinding.etInputLink.setText(data.urlMdm)
                        mClickDownload = true
                    } catch (_: Exception) {
                    }
                }
            }
        }
        mMdmBinding.tvDownload.setOnClickListener {
            val searchEnter = mTempLink ?: mMdmBinding.etInputLink.text.trim().toString()
            if (searchEnter.isEmpty()) {
                showToastIDMdm(R.string.mdm_parsed_content_cannot_empty)
                return@setOnClickListener
            }
            mTempLink = null
            mDialogInitMdmLoading = DialogInitMdmLoading(this, R.string.mdm_loading)
            mDialogInitMdmLoading?.show()
            mSearchCountMdm = 0
            mSearchText = searchEnter
            requestMethodMdm(searchEnter)
        }
        mMdmBinding.tvPastLink.setOnClickListener {
            MdmTotalUtils.getClipTextMdm(mMdmClipText)?.let {
                mMdmBinding.etInputLink.setText(it)
            }
        }
        mMdmBinding.ivClearInput.setOnClickListener {
            mMdmBinding.etInputLink.text = null
        }
        mMdmBinding.layoutTopSet.ivHelp.setOnClickListener {
            startActivity(Intent(this, MdmHelpYouActivity::class.java))
        }
        if (mClickDownload) {
            mClickDownload = false
            mMdmBinding.tvDownload.performClick()
        }
        if (!MdmTotalUtils.getMdmAppStatus()) {
            val a = Random.nextInt(0, 2)
            if (a == 0) {
                mMdmBinding.etInputLink.setText("https://pin.it/3ZJBGLm4F")
            } else {
                mMdmBinding.etInputLink.setText("https://x.com/Axaxia88/status/1952701121233051850")
            }
        }
        lifecycleScope.launch(Dispatchers.Main) {
            delay(288)
            MdmDealAdUtils.loadBookIntersMdm()
        }
    }

    private var mResolvingText = ""
    private fun delaResolvingResult() {
        runOnUiThread {
            when (mResolvingText) {
                "success" -> {
                    showBookAdMdm("", true) {
                        mDialogInitMdmLoading.dismissGoMdm()
                        startActivity(Intent(this, MdmFormatChooseActivity::class.java).apply {
//                        putExtra("typeSearch", mTypeSearch)
//                        putExtra("dvsNotifyType", mDvsNotifyType)
                        })
                    }
                }

                "noData" -> {
                    showBookAdMdm("", true) {
                        mMdmBinding.tvDownload.visibility = View.GONE
                        mDialogInitMdmLoading.dismissGoMdm()
                        showToastIDMdm(R.string.mdm_please_try_again_or_change)
                    }
                }

                "failed" -> {
                    if (mSearchCountMdm == 1) {
                        showBookAdMdm("", true) {
                            mSearchCountMdm = 0
                            mDialogInitMdmLoading.dismissGoMdm()
                            showToastIDMdm(R.string.mdm_please_try_again_or_change)
                        }
                    } else {
                        lifecycleScope.launch {
                            delay(Random.nextInt(3000, 4000).toLong())
                            mSearchCountMdm++
                            requestMethodMdm(mSearchText)
                        }
                    }
                }
            }
        }
    }

    private fun requestMethodMdm(searchEnter: String) {
        val bodyRequest = JSONObject().apply {
            put("url", searchEnter)  // 放在 raw 中的字段
        }
        val requestQueue = Volley.newRequestQueue(this)
        val jsonObjectRequest: StringRequest =
            object :
                StringRequest(
                    Method.POST, "https://api.savervideo.vn/v1/social/autolink".replace(
                        "savervideo", "zm.io"
                    ), Response.Listener {
                        val moshi = Moshi.Builder().build()
                        val moshiAdapter = moshi.adapter(DataLinkValueMdm::class.java)
                        val listVideos = mutableListOf<DataDownloadingMdm>()
                        try {
                            it?.let {
                                moshiAdapter.fromJson(it)?.let { videoData ->
                                    if (videoData.mdmSource != "x"
                                        && videoData.mdmSource != "twitter" && videoData.mdmSource != "pinterest"
                                    ) {
                                        mResolvingText = "failed"
                                        delaResolvingResult()
                                        return@Listener
                                    }
                                    videoData.mdmMedias?.let { medias ->
                                        for (dia in medias) {
                                            if (!dia.mdmUrl.isNullOrEmpty()) {
                                                val bean = DataDownloadingMdm(
                                                    videoData.mdmTitle
                                                        ?: getString(R.string.mdm_no_title),
                                                    if (videoData.mdmType == "image"
                                                        || videoData.mdmType == "photo"
                                                    ) {
                                                        dia.mdmUrl
                                                    } else {
                                                        (dia.mdmThumbnail ?: videoData.mdmThumbnail)
                                                            ?: dia.mdmUrl
                                                    }, dia.mdmUrl, dia.mdmQuality ?: "SD"
                                                ).apply {
                                                    videoExtensionMdm = dia.mdmExtension ?: "mp4"
                                                    videoMediaTypeMdm = dia.mdmType ?: "video"
                                                }
                                                listVideos.add(bean)
                                            }
                                        }

                                    }
                                }
                            }
                        } catch (_: Exception) {
                        } finally {
                            if (listVideos.isNotEmpty()) {
                                mResolvingText = "success"
                                mParseLinksList.clear()
                                mParseLinksList.addAll(listVideos)
                                delaResolvingResult()
                            } else {
                                mResolvingText = "noData"
                                delaResolvingResult()
                            }
                        }
                    }, Response.ErrorListener {
                        mResolvingText = "failed"
                        delaResolvingResult()
                    }) {
                override fun getBodyContentType(): String {
                    return "application/json; charset=utf-8"
                }

                override fun getHeaders(): Map<String, String>? {
                    val map = HashMap<String, String>()
                    val key =
                        DataManagerMdmUtils.getDataKeyMdm(MDM_ALL_TWO_KEY, MDM_ALL_TWO_KEY_VALUES)
                            .mdmBaseResult64().replace("_fast_saver_12", "")
                    map["apikey"] = key
                    map["Content-Type"] = "application/json"
                    return map
                }

                override fun getBody(): ByteArray? {
                    val body = bodyRequest.toString().toByteArray()
                    return body
                }
            }
        requestQueue.add(jsonObjectRequest)
    }

    override fun onResume() {
        super.onResume()
        lifecycleScope.launch(Dispatchers.Main) {
            if (!MdmTotalUtils.getMdmAppStatus()) {
                launch(Dispatchers.Main) {
                    addVideos()
                }
            } else {
                launch(Dispatchers.IO) {
                    addVideos2()
                }
            }
        }
    }

    private fun addVideos() {
        if (mMdmBinding.flVideo1.hasOnClickListeners()) return
        val linkEp1 = "https://pin.it/4aKhk84Py"
        val linkEp2 = "https://x.com/Bcntrending/status/1828123034626249142"
        val imageEp1 = R.drawable.mdm_pic_511
        val imageEp2 = R.drawable.mdm_pic_512
        mMdmBinding.ivVideoImage1.load(imageEp1) {
            transformations(RoundedCornersTransformation(16f.mdmGetPxDp()))
        }
        mMdmBinding.ivVideoImage2.load(imageEp2) {
            transformations(RoundedCornersTransformation(16f.mdmGetPxDp()))
        }
        mMdmBinding.flVideo1.setOnClickListener {
            mTempLink = linkEp1
            mMdmBinding.etInputLink.text = null
            mMdmBinding.tvDownload.performClick()
        }
        mMdmBinding.flVideo2.setOnClickListener {
            mTempLink = linkEp2
            mMdmBinding.etInputLink.text = null
            mMdmBinding.tvDownload.performClick()
        }
        mMdmBinding.flVideo1.visibility = View.VISIBLE
        mMdmBinding.flVideo2.visibility = View.VISIBLE
    }

    private suspend fun addVideos2() {
        try {
            if (mMdmBinding.flVideo1.hasOnClickListeners()) return
            if (mVideoMdmList.isEmpty()) {
                ApplicationMdmUtils.getMeteorVideoSome()
            }
            val mIndex = Random.nextInt(10, 50)
            val linkEp1 = mVideoMdmList[mIndex].urlMdm
            val linkEp2 = mVideoMdmList[mIndex + 1].urlMdm
            val imageEp1 = MdmTotalUtils.getClueForBitmap(this, mIndex + 1)
            val imageEp2 = MdmTotalUtils.getClueForBitmap(this, mIndex + 2)
            withContext(Dispatchers.Main) {
                mMdmBinding.ivVideoImage1.load(imageEp1) {
                    transformations(RoundedCornersTransformation(16f.mdmGetPxDp()))
                }
                mMdmBinding.ivVideoImage2.load(imageEp2) {
                    transformations(RoundedCornersTransformation(16f.mdmGetPxDp()))
                }
                mMdmBinding.flVideo1.setOnClickListener {
                    mTempLink = linkEp1
                    mMdmBinding.etInputLink.text = null
                    mMdmBinding.tvDownload.performClick()
                }
                mMdmBinding.flVideo2.setOnClickListener {
                    mTempLink = linkEp2
                    mMdmBinding.etInputLink.text = null
                    mMdmBinding.tvDownload.performClick()
                }
                mMdmBinding.flVideo1.visibility = View.VISIBLE
                mMdmBinding.flVideo2.visibility = View.VISIBLE
            }
        } catch (_: Exception) {
        }
    }

    private fun showBookAdMdm(
        type: String, showTip: Boolean = false, statusLook: Boolean = true, mdmBack: () -> Unit
    ) {
        if (statusLook && !MdmTotalUtils.getMdmAppStatus()) {
            mdmBack()
            return
        }
        if (showTip) {
            if (MdmDealAdUtils.getVlaueForInters() != null) {
                showRootBookAdBack(type, statusLook, mdmBack)
                return
            }
            val dialog = DialogInitMdmLoading(this)
            dialog.show()
            MdmDealAdUtils.loadBookIntersMdm(true, statusLook)
            lifecycleScope.launch(Dispatchers.Main) {
                delay(1600)
                if (MdmDealAdUtils.getVlaueForInters() != null) {
                    showRootBookAdBack(type, statusLook, mdmBack)
                    delay(96)
                    dialog.dismissGoMdm()
                    return@launch
                }
                if (MdmDealAdUtils.getVlaueForInters() != null) {
                    delay(1600)
                    showRootBookAdBack(type, statusLook, mdmBack)
                    delay(100)
                    dialog.dismissGoMdm()
                    return@launch
                }
                delay(1600)
                showRootBookAdBack(type, statusLook, mdmBack)
                delay(96)
                dialog.dismissGoMdm()
            }
        } else {
            showRootBookAdBack(type, statusLook, mdmBack)
        }
    }

    override fun getLayoutValue(): ActivityMdmInputLinkBinding {
        return ActivityMdmInputLinkBinding.inflate(layoutInflater)
    }
}